<template>
  <div class="user-form">
    <cell-group inset>
  <field
    v-model="phone"
    required
    label="手机号"
    placeholder="请输入你要注册的手机号"
    :error-message="error" 
    @blur="confirm"
  />
  <field
    v-model="sms"
    center
    clearable
    label="短信验证码"
    placeholder="请输入短信验证码"
  >
    <template #button>
      <Button size="small" type="primary" @click="codeHandle">发送验证码</Button>
    </template>
  </field>
</cell-group>
<div style="margin: 16px;">
    <Button round block type="primary" @click="regHandle">
      立即注册
    </Button>
</div>
  <div style="margin: 16px;">
    <Button round block type="default" :to="'/'">
      暂不注册
    </Button>
  </div>
</div>
</template>
<style scoped>
.user-form {
  padding: 8px;
}
</style>
<script setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { setToken } from "../utils/tools";
import { codeAPI } from "../services/auth";
import { regAPI } from "../services/auth";
import { stringify } from "qs";
import { Form, Field, CellGroup,Button,Toast } from 'vant';
const phone = ref("");
const error = ref("");
const { replace } = useRouter();
const router = useRouter();
const sms = ref("");
var flag=0;//验证手机号是否输入 0表示未输入，1表示已经输入
// 验证手机号格式
var code='';
const confirm=()=>{
  var reg=/^1(3|4|5|6|7|8|9)\d{9}$/;
  if (reg.test(phone.value)){
     error.value="";
     flag=1;
  }else{
     error.value="手机号格式错误";
  }
}
// 接收验证码
const codeHandle=async()=>{
   if(flag==1){
     const res=await codeAPI({mobile:phone.value});
     console.log(res);
     if(res.code){
      alert("您的验证码是"+res.data);
      code=res.data;
     }
   }else{
    alert("请先输入手机号");
   }
}
// 注册验证
const regHandle=async()=>{
  const data = {
    mobile: phone.value,
    code: sms.value,
  };
  if(flag==1){
    if(code==sms.value&&code!=''){
      // 执行注册
      const res = await regAPI(stringify(data));
      console.log(res);
      if (res.code === 200) {
        Toast.success("注册成功");
        setToken(res.data);
        replace({
          name: "User",
        });
      } else {
        alert(res.msg);
      }
  }else if(sms.value==''){
    Toast.fail("请输入验证码");
  }
  else{
    Toast.fail("验证码错误");
  }
  }else{
    alert("请先输入手机号");
  }
}
</script>
